package com.example.demo;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;

import java.io.IOException;


/**
 * @author Fuzhengwei bugstack.cn @小傅哥
 * @description 发送MQ消息任务队列
 * @create 2024-04-06 10:47
 */

@Component()
public class SendMessageTaskJob {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ConnectionFactory connectionFactory;

    @Scheduled(cron = "0/5 * * * * ?")
    public void exec_db01() throws IOException {
        Channel channel = connectionFactory.createConnection().createChannel(false);

        // 拉取消息
        Message message = rabbitTemplate.receive("directQueueTx");
        if (message != null) {
            String msgBody = new String(message.getBody());
            long deliveryTag = message.getMessageProperties().getDeliveryTag(); // 获取消息的 deliveryTag

            try {
                System.out.println("开始处理消息: " + msgBody);
                Thread.sleep(1000); // 模拟消息处理

                // 消息处理成功，手动 ACK
                channel.basicAck(deliveryTag, false);
                System.out.println("消息处理成功: " + msgBody);
            } catch (Exception e) {
                // 消息处理失败，拒绝并重新入队
                channel.basicNack(deliveryTag, false, true);
                System.err.println("消息处理失败，重新入队: " + msgBody);
            }
        } else {
            System.out.println("队列中没有消息，等待下次拉取...");
        }
    }



}
